package sk.octopuss.archery.web;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import sk.octopuss.archery.domain.Brand;
import sk.octopuss.archery.domain.Category;
import sk.octopuss.archery.domain.Item;
import sk.octopuss.archery.service.BrandService;
import sk.octopuss.archery.service.CategoryService;
import sk.octopuss.archery.service.ItemService;


@RequestMapping("/items")
@Controller
public class ItemController extends AbstractController 	{
		
		@Autowired
		private ItemService itemService;
		@Autowired
		private CategoryService categoryService;
		@Autowired
		private BrandService brandService;
		

		
		@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	    public String show(@PathVariable("id") final Long id, final Model uiModel) {
			final Item item = itemService.find(id);
			 uiModel.addAttribute(item);
			uiModel.addAttribute("categories",itemService.getParentCategoriesFromTop(item));
	        return "items/show";
	    }
		
		@RequestMapping(method = RequestMethod.GET)
	    public String list(@RequestParam(value = "page", required = false) final Integer page, @RequestParam(value = "size", required = false) final Integer size, final Model uiModel) {
	        if (page != null || size != null) {
	            final int sizeNo = size == null ? 10 : size.intValue();
	            uiModel.addAttribute("items", itemService.findAllEntries(page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo));
	            final float nrOfPages = (float) itemService.countItems() / sizeNo;
	            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
	        } else {
	            uiModel.addAttribute("items", itemService.findAll());
	        }
	        return "items/list";
	    }
		
		@RequestMapping(method = RequestMethod.POST)
	    public String create(@Valid final Item item, final BindingResult bindingResult, final Model uiModel, final HttpServletRequest httpServletRequest) {
	        if (bindingResult.hasErrors()) {
	            uiModel.addAttribute("item", item);
	            return "items/create";
	        }
	        uiModel.asMap().clear();
	        itemService.save(item);
	        return "redirect:/items/" + encodeUrlPathSegment(item.getId().toString(), httpServletRequest);
	    }

		@RequestMapping(params = "form", method = RequestMethod.GET)
	    public String createForm(final Model uiModel) {
	        uiModel.addAttribute("item", new Item());
	       // uiModel.addAttribute("categories",categoryService.getAllTreePaths());
	        return "items/create";
	    }
		
		@RequestMapping(method = RequestMethod.PUT)
	    public String update(@Valid final Item item, final BindingResult bindingResult, final Model uiModel, final HttpServletRequest httpServletRequest) {
	        if (bindingResult.hasErrors()) {
	            uiModel.addAttribute("item", item);
	            return "items/update";
	        }
	        uiModel.asMap().clear();
	        itemService.save(item);
	        return "redirect:/items/" + encodeUrlPathSegment(item.getId().toString(), httpServletRequest);
	    }

		@RequestMapping(value = "/{id}", params = "form", method = RequestMethod.GET)
	    public String updateForm(@PathVariable("id") final Long id, final Model uiModel) {
	        uiModel.addAttribute("item", itemService.find(id));
	        return "items/update";
	    }
		@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	    public String delete(@PathVariable("id") final Long id, @RequestParam(value = "page", required = false) final Integer page, @RequestParam(value = "size", required = false) final Integer size, final Model uiModel) {
	        itemService.remove(itemService.find(id));
	        uiModel.asMap().clear();
	        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
	        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
	        return "redirect:/items";
	    }
		@ModelAttribute("brands")
	    public Collection<Brand> populateBrands() {
	        return brandService.findAll();
	    }
		@ModelAttribute("categories")
		public Collection<Category> populateCategories() {
			return categoryService.findAll();
		}
		@ModelAttribute("testCategories")
		public Map<Category,List<String>> populateCategoryTrees() {
			return categoryService.getAllTreePaths();
		}

//		@ModelAttribute("username")
//		public String populateUser(){
//			final User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//		     return user.getUsername(); //get logged in username
//		}

		
}
